﻿using Cordyceps.Demo.SqlServer.DbMigrator.EFCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Cordyceps.Demo.SqlServer.DbMigrator;

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();

        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            try
            {
                var dbContext = services.GetRequiredService<DemoMigrationsDbContext>();
                // 执行所有未应用的迁移
                dbContext.Database.Migrate();
                Console.WriteLine("Migration completed successfully.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred during migration: {ex.Message}");
            }
        }

        Console.ReadLine();
    }

    public static IHostBuilder CreateHostBuilder(string[] args)
    {
        return Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                services.AddDbContext<DemoMigrationsDbContext>(options =>
                    options.UseSqlServer(hostContext.Configuration.GetConnectionString("Default")));
            });
    }
}